import React, { useEffect } from 'react';
import { Modal, Form, Select, Row } from 'antd';
import classNames from 'classnames';
import { useDynamicList } from '@/hooks';
import { trim, omit } from 'lodash';

import { NumberSettingInput, PercentSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';

import cpfSettingStyle from './index.less';

const cpfFormulaType = {
    TW: 2,
    FIX: 1
};

const skillFormulaTypeEnum = {
    [cpfFormulaType.TW]: {
        value: cpfFormulaType.TW,
        text: '百分比'
    },
    [cpfFormulaType.FIX]: {
        value: cpfFormulaType.FIX,
        text: '固定值'
    }
};

const FormulaTypeSelect = React.forwardRef(({ value, onChange, className }, ref) => (
    <Select
        value={value}
        onChange={onChange}
        className={classNames(cpfSettingStyle.formulaTypeSelect, className)}
        ref={ref}
    >
        {Object.values(skillFormulaTypeEnum).map(item => (
            <Select.Option key={item.value} value={item.value}>
                {item.text}
            </Select.Option>
        ))}
    </Select>
));

const ShareInput = ({ index, dataSource, sdlPayStyle, onUpdate, style }) => {
    let content;
    const errorFieldMap = dataSource?.vvValidateInfo?.errorField || {};
    switch (sdlPayStyle) {
        case cpfFormulaType.TW:
            content = (
                <span >
                    <PercentSettingInput
                        value={dataSource.sdlRate}
                        onChange={value => {
                            onUpdate('sdlRate', value, index, dataSource);
                        }}
                        suffix="%"
                        className={classNames(cpfSettingStyle.input, {
                            [cpfSettingStyle.error]: errorFieldMap?.sdlRate
                        })}
                        nonNegative
                    /> <span>(TW)</span>
                </span>
            );
            break;

        case cpfFormulaType.FIX:
            content = (
                <>
                    <NumberSettingInput
                        prefix="$"
                        value={dataSource.sdlAmt || ''}
                        onChange={value => {
                            onUpdate('sdlAmt', value, index, dataSource);
                        }}
                        className={classNames(cpfSettingStyle.input, {
                            [cpfSettingStyle.error]: errorFieldMap?.sdlAmt
                        })}
                        align="left"
                        nonNegative
                    />
                </>
            );
            break;

        default:
            content = (
                <>
                    <NumberSettingInput
                        prefix="$"
                        onChange={value => {
                            onUpdate('sdlAmt', value, index, dataSource);
                        }}
                        value={dataSource.sdlAmt || ''}
                        className={classNames(cpfSettingStyle.input, {
                            [cpfSettingStyle.error]: errorFieldMap?.sdlAmt
                        })}
                        align="left"
                        nonNegative
                    />
                </>
            );
    }

    return (
        <div className={cpfSettingStyle.shareInput} style={{ ...style }}>
            {content}
        </div>
    );
};
ShareInput.defaultProps = {
    style: {}
};

const ShareRowValidateResult = ({ validateInfo }) => (
    <div className={cpfSettingStyle.validateBox}>{validateInfo}</div>
);

const ShareItem = ({ form, index, dataSource, typeChange, onUpdate }) => {
    const errorFieldMap = dataSource?.vvValidateInfo?.errorField || {};
    return (
        <div className={cpfSettingStyle.row} >
            <Row className={classNames(cpfSettingStyle.shareItem, cpfSettingStyle.shareInputItem)}>
                <FormulaTypeSelect
                    onChange={type => typeChange(type, index, dataSource)}
                    value={dataSource.sdlPayStyle}
                    placeholder="请选择"
                    className={classNames({ [cpfSettingStyle.error]: errorFieldMap?.sdlPayStyle })}
                />
                <ShareInput
                    index={index}
                    dataSource={dataSource}
                    sdlPayStyle={dataSource.sdlPayStyle}
                    form={form}
                    onUpdate={onUpdate}
                />
            </Row>

            <div >
                <ShareRowValidateResult validateInfo={dataSource?.vvValidateInfo?.message} />
            </div>
        </div>
    );
};

/**
 * 校验行数据
 * @param record
 * @returns {{errorField, message}}
 */
const validateRow = record => {
    const errorField = {};
    const errorMessages = [];

    const validateResult = (fieldMap, messages) => ({
        errorField: fieldMap,
        message: messages.join(', ')
    });


    if (record.sdlPayStyle === cpfFormulaType.FIX) {
        if (!trim(record.sdlAmt)) {
            errorField.sdlAmt = true;
            errorMessages[0] = '请输入固定值'
        }
    }

    if (record.sdlPayStyle === cpfFormulaType.TW) {
        if (!trim(record.sdlRate)) {
            errorField.sdlRate = true;
            errorMessages[0] = '请输入百分比'
        }
    }

    return errorMessages.length === 0 ? validateResult({}, []) : validateResult(errorField, errorMessages);
};

const mapRows = (rows, callback) => {
    if (!rows) {
        return rows;
    }

    if (Array.isArray(rows)) {
        return rows.map(row => ({ ...row, ...callback(row) }));
    }

    return { ...rows, ...callback(rows) };
};

/**
 * 添加校验信息
 * @param {Array | Object} rows
 * @returns {(*&{validateInfo: {errorField, message}})|*}
 */
const addValidateInfo = rows => mapRows(rows, row => ({ vvValidateInfo: validateRow(row) }));
/**
 * 雇主扣除额模态框
 */
const EditItem = ({ form, title, visible, model, onCancel, onOk }) => {
    const { list: dataSource, resetList: resetDataSource, getKey, replace } = useDynamicList([]);
    const handleTypeChange = (type, index, record) => {
        replace(index, { ...record, sdlPayStyle: type });
    };

    const handleOk = () => {
        const newDataSource = addValidateInfo(dataSource);
        resetDataSource(newDataSource);
        // 如果校验不通过
        if (newDataSource.find(data => trim(data.vvValidateInfo.message))) {
            return;
        }
        onOk(omit(dataSource[0], ['vvValidateInfo', 'vvShowMax', 'message', 'errorField', 'vv_id']));
    };

    const handleRowUpdate = (field, fieldValue, index, record) => {
        const newRecord = addValidateInfo({ ...record, [field]: fieldValue });
        replace(index, newRecord);
    };

    useEffect(() => {
        if (model) {
            // resetDataSource(addValidateInfo(Array.isArray(model) ? model : [model]));
            resetDataSource(Array.isArray(model) ? model : [model]);
        }
    }, [model, resetDataSource]);

    return (
        <Modal title={title} visible={visible} onCancel={onCancel} onOk={handleOk} width={500}>
            <div className={cpfSettingStyle.cpfContributionsModal}>
                <Form className={cpfSettingStyle.shareBox} layout="inline">
                    {dataSource.map((data, index) => (
                        <ShareItem
                            key={getKey(index)}
                            index={index}
                            dataSource={data}
                            typeChange={handleTypeChange}
                            onUpdate={handleRowUpdate}
                            form={form}
                        />
                    ))}
                </Form>
            </div>
        </Modal>
    );
};
EditItem.defaultProps = {
    title: '新增',
    model: [{}],
    onCancel: () => { },
    onOk: () => { },
    dataSource: []
};

export default Form.create({})(EditItem);
